package net.borderwars.convert;

import java.io.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * @author Eric
 *         Date: Mar 5, 2005
 *         Time: 3:48:42 PM
 */
public class convert {
    ArrayList toConvert = new ArrayList ();

    public static void main (String[] args) throws IOException, InterruptedException {
        if (args.length != 1) {
            System.out.println ("Please tell me where to find some .R files to convert");
        }
        File sourceDir = new File (args[0]);
        File crobots[] = sourceDir.listFiles (new FileFilter() {
            public boolean accept (File pathname) {
                if (pathname.getAbsolutePath ().endsWith (".R") || pathname.getAbsolutePath ().endsWith (".r"))
                    return (true);
                return (false);
            }
        });
        convert c = new convert (crobots);
    }

    public void dumb () throws SQLException {
        ResultSet grs = null;
        ArrayList rows = new ArrayList ();
        while (grs.next ()) {
            float row[] = {grs.getFloat (1), grs.getFloat (2)};
            rows.add (row);
        }

        float data[][] = new float[2][rows.size ()];
        int rowNum = 0;
        Iterator i = rows.iterator ();
        while (i.hasNext ()) {
            float row[] = (float[]) i.next ();
            data[rowNum] = row;
            rowNum++;
        }
    }

    public convert (File crobots[]) throws IOException, InterruptedException {
        String cmd = "c:\\data\\borderwars\\crobots\\crobots.exe -c ";
        for (int i = 0; i < 5; i++) {
            File crobot = crobots[i];
            Process p = Runtime.getRuntime ().exec (cmd + crobot.getAbsolutePath ());

            p.getOutputStream ().write ('\n');
            p.getOutputStream ().flush ();

            InputStream is = p.getInputStream ();
            InputStreamReader isr = new InputStreamReader (is);
            BufferedReader br = new BufferedReader (isr);
            System.out.println ("Converting " + i + " " + crobot.getAbsolutePath ());
            CRobot c = new CRobot (br);
            c.setName (crobot.getName ().substring (0, crobot.getName ().indexOf (".")));
            byte data[] = c.makeJavaClass (crobot.getAbsolutePath ());

            File f = new File (c.getName () + ".class");
            BufferedOutputStream bos = new BufferedOutputStream (new FileOutputStream (f));
            bos.write (data);
            bos.flush ();
            bos.close ();
            System.err.println ("Wrote out " + f.getAbsolutePath ());

            p.destroy ();
        }
    }

}
